package com.diandian.backend.product.service;

import com.alibaba.fastjson.JSON;
import com.diandian.backend.product.clients.*;
import com.diandian.backend.product.clients.dto.client.ClientSettingGetByBelongRespDTO;
import com.diandian.backend.product.clients.dto.elemeRetail.ElemeRetailBusinessGetSkuStockRespDTO;
import com.diandian.backend.product.clients.dto.elemeRetail.ElemeRetailGetSkuStockReqDTO;
import com.diandian.backend.product.clients.dto.jingdongHome.JingdongHomeBatchQueryUseableInfoReq;
import com.diandian.backend.product.clients.dto.jingdongHome.JingdongHomeBatchQueryUseableInfoReqData;
import com.diandian.backend.product.clients.dto.jingdongHome.JingdongHomeBusinessGetProductSkuInfoRespDTO;
import com.diandian.backend.product.clients.dto.meituanShangou.MeituanShangouBusinessGetProductSkuInfoRespDTO;
import com.diandian.backend.product.clients.dto.meituanShangou.MeituanShangouGetProductSkuInfoReqDTO;
import com.diandian.backend.product.clients.dto.third.ThirdSkuStockQueryParamDTO;
import com.diandian.backend.product.clients.dto.third.ThirdStoreStockDTO;
import com.diandian.backend.product.param.ProductStockSummaryGetAllParam;
import com.diandian.backend.product.resp.ProductStockSummaryGetAllResp;
import com.diandian.base.boot.starter.response.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ProductStockSummaryService {

    @Autowired
    private DianDianThirdExchangeClient dianDianThirdExchangeClient;

    @Autowired
    private DianDianMeituanShangouExchangeClient dianDianMeituanShangouExchangeClient;

    @Autowired
    private DianDianClientClient dianDianClientClient;

    @Autowired
    private DianDianElemeRetailExchangeClient dianDianElemeRetailExchangeClient;

    @Autowired
    private DianDianJingdongHomeExchangeClient dianDianJingdongHomeExchangeClient;

    public List<ProductStockSummaryGetAllResp> getAllStockSummary(ProductStockSummaryGetAllParam data){

        data.check();

        String belong = data.getBelong();
        String offlineStoreCode = data.getOfflineStoreCode();
        String productCode = data.getProductCode();
        String skuCode = data.getSkuCode();

        List<ProductStockSummaryGetAllResp> resultList = new ArrayList<>();

        // 查询本地库存：目前支持现货库存、可用库存、在途库存数据、预占库存
        ThirdSkuStockQueryParamDTO thirdSkuStockQueryParamDTO = new ThirdSkuStockQueryParamDTO();
        thirdSkuStockQueryParamDTO.setSource(belong);
        thirdSkuStockQueryParamDTO.setProductCode(data.getProductCode());
        thirdSkuStockQueryParamDTO.setSkuCode(data.getSkuCode());
        thirdSkuStockQueryParamDTO.setStoreCode(offlineStoreCode);
        // 执行查询
        ProductStockSummaryGetAllResp thirdData = null;
        try {
            BaseResult<ThirdStoreStockDTO> thirdResponse = dianDianThirdExchangeClient.skuStockQuery(thirdSkuStockQueryParamDTO);
            if(thirdResponse != null){
                if(thirdResponse.getCode() == 0){
                    thirdData = new ProductStockSummaryGetAllResp();
                    thirdData.setType("local");
                    thirdData.setOfflineStoreCode(thirdResponse.getData().getStoreCode());
                    thirdData.setProductCode(thirdResponse.getData().getProductCode());
                    thirdData.setSkuCode(thirdResponse.getData().getSkuCode());
                    thirdData.setCurQty(thirdResponse.getData().getCurQty());
                    thirdData.setTranQty(thirdResponse.getData().getTranQty());
                    thirdData.setInQty(thirdResponse.getData().getInQty());
                    thirdData.setPreQty(thirdResponse.getData().getPreQty());
                    thirdData.setLockQty(null);
                    thirdData.setLastModificationTime(thirdResponse.getData().getLastModificationTime());
                    thirdData.setQueryMessage(null);
                    thirdData.setFixedFlag(false);
                    thirdData.setFixeMessage(null);
                    resultList.add(thirdData);
                } else {
                    thirdData = new ProductStockSummaryGetAllResp();
                    thirdData.setType("local");
                    thirdData.setOfflineStoreCode(offlineStoreCode);
                    thirdData.setProductCode(productCode);
                    thirdData.setSkuCode(skuCode);
                    thirdData.setCurQty(null);
                    thirdData.setTranQty(null);
                    thirdData.setInQty(null);
                    thirdData.setPreQty(null);
                    thirdData.setLockQty(null);
                    thirdData.setLastModificationTime(null);
                    thirdData.setQueryMessage("未查询到库存数据");
                    thirdData.setFixedFlag(false);
                    thirdData.setFixeMessage(null);
                    resultList.add(thirdData);
                }
            }
        } catch (Exception e) {
            thirdData = new ProductStockSummaryGetAllResp();
            thirdData.setType("local");
            thirdData.setOfflineStoreCode(offlineStoreCode);
            thirdData.setProductCode(productCode);
            thirdData.setSkuCode(skuCode);
            thirdData.setCurQty(null);
            thirdData.setTranQty(null);
            thirdData.setInQty(null);
            thirdData.setPreQty(null);
            thirdData.setLockQty(null);
            thirdData.setLastModificationTime(null);
            thirdData.setQueryMessage("查询异常");
            thirdData.setFixedFlag(false);
            thirdData.setFixeMessage(null);
            resultList.add(thirdData);
        }

        Map<String, String> settingMap = getAllSettingMap(belong);

        // 查询美团库存: 只有一个库存数据，作为可用现货处理
        ProductStockSummaryGetAllResp mtsgData;
        String mtsgAppKey = settingMap.get("meiTuanShanGou.appKey");
        String mtsgAppSecret = settingMap.get("meiTuanShanGou.appSecret");
        if(mtsgAppKey != null && !"".equals(mtsgAppKey) && mtsgAppSecret != null && !"".equals(mtsgAppSecret)) {
            MeituanShangouGetProductSkuInfoReqDTO mtsgDTO = new MeituanShangouGetProductSkuInfoReqDTO();
            mtsgDTO.setOfflineStoreCode(offlineStoreCode);
            mtsgDTO.setProductCode(productCode);
            mtsgDTO.setSkuCode(skuCode);
            BaseResult mtsgResp = dianDianMeituanShangouExchangeClient.getProductSkuStockInfo(mtsgAppKey, mtsgAppSecret, belong, mtsgDTO);
            if(mtsgResp != null) {
                // 查到库存数据
                if(mtsgResp.getCode() == 0 && mtsgResp.getData() != null){
                    List<MeituanShangouBusinessGetProductSkuInfoRespDTO> dataList = JSON.parseArray(JSON.toJSONString(mtsgResp.getData()), MeituanShangouBusinessGetProductSkuInfoRespDTO.class);

                    MeituanShangouBusinessGetProductSkuInfoRespDTO item = dataList.get(0);
                    mtsgData = new ProductStockSummaryGetAllResp();
                    mtsgData.setType("meituanShangou");
                    mtsgData.setOfflineStoreCode(item.getOfflineStoreCode());
                    mtsgData.setOnlineStoreCode(item.getOnlineStoreCode());
                    mtsgData.setProductCode(item.getProductCode());
                    mtsgData.setSkuCode(item.getSkuCode());
                    mtsgData.setCurQty(item.getCurQty());
                    mtsgData.setTranQty(item.getTranQty());
                    mtsgData.setInQty(item.getInQty());
                    mtsgData.setPreQty(item.getPreQty());
                    mtsgData.setLockQty(null);
                    mtsgData.setLastModificationTime(item.getLastModificationTime());
                    mtsgData.setQueryMessage(null);

                    // 线下库存为空
                    if(thirdData == null){
                        mtsgData.setFixedFlag(false);
                        mtsgData.setFixeMessage(null);
                    } else {
                        Long thirdDataInQty = thirdData.getInQty() == null ? 0L : thirdData.getInQty();
                        Long mtsgDataInQty = mtsgData.getInQty() == null ? 0L : mtsgData.getInQty();
                        mtsgData.setFixedFlag(Long.compare(thirdDataInQty, mtsgDataInQty) != 0);
                        mtsgData.setFixeMessage("库存同步");
                    }
                    resultList.add(mtsgData);
                } else {
                    mtsgData = new ProductStockSummaryGetAllResp();
                    mtsgData.setType("meituanShangou");
                    mtsgData.setOfflineStoreCode(offlineStoreCode);
                    mtsgData.setOnlineStoreCode(null);
                    mtsgData.setProductCode(productCode);
                    mtsgData.setSkuCode(skuCode);
                    mtsgData.setCurQty(null);
                    mtsgData.setTranQty(null);
                    mtsgData.setInQty(null);
                    mtsgData.setPreQty(null);
                    mtsgData.setLockQty(null);
                    mtsgData.setLastModificationTime(null);
                    mtsgData.setQueryMessage(mtsgResp.getMessage());
                    mtsgData.setFixedFlag(false);
                    mtsgData.setFixeMessage(null);
                    resultList.add(mtsgData);
                }
            }
        }

        // 查询京东库存： 有多个库存数据
        ProductStockSummaryGetAllResp jingdongHomeData;
        String jingdongHomeAppKey = settingMap.get("jingDongHome.appKey");
        String jingdongHomeAppSecret = settingMap.get("jingDongHome.appSecret");
        String jingdongHomeOperator = settingMap.get("jingDongHome.operator");
        if(jingdongHomeAppKey != null && !"".equals(jingdongHomeAppKey) && jingdongHomeAppSecret != null && !"".equals(jingdongHomeAppSecret)) {

            // 查询库存数据
            JingdongHomeBatchQueryUseableInfoReq stockQueryDTO = new JingdongHomeBatchQueryUseableInfoReq();
            JingdongHomeBatchQueryUseableInfoReqData itemDTO = new JingdongHomeBatchQueryUseableInfoReqData();
            itemDTO.setOfflineStoreCode(offlineStoreCode);
            itemDTO.setSkuCode(skuCode);
            stockQueryDTO.setData(Arrays.asList(itemDTO));
            BaseResult stockResp = dianDianJingdongHomeExchangeClient.queryOpenUseable(jingdongHomeAppKey, jingdongHomeAppSecret, null, jingdongHomeOperator, belong, stockQueryDTO);

            // 解析处理响应数据
            if(stockResp != null) {

                // 查到库存数据
                if(stockResp.getCode() == 0 && stockResp.getData() != null){
                    List<JingdongHomeBusinessGetProductSkuInfoRespDTO> dataList = JSON.parseArray(JSON.toJSONString(stockResp.getData()), JingdongHomeBusinessGetProductSkuInfoRespDTO.class);

                    JingdongHomeBusinessGetProductSkuInfoRespDTO item = dataList.get(0);

                    jingdongHomeData = new ProductStockSummaryGetAllResp();
                    jingdongHomeData.setType("jingdongHome");
                    jingdongHomeData.setOfflineStoreCode(item.getOfflineStoreCode());
                    jingdongHomeData.setOnlineStoreCode(item.getOnlineStoreCode());
                    jingdongHomeData.setProductCode(item.getProductCode());
                    jingdongHomeData.setSkuCode(item.getSkuCode());
                    jingdongHomeData.setCurQty(item.getCurQty());
                    jingdongHomeData.setTranQty(item.getTranQty());
                    jingdongHomeData.setInQty(item.getInQty());
                    jingdongHomeData.setPreQty(item.getPreQty());
                    jingdongHomeData.setLockQty(item.getLockQty());
                    jingdongHomeData.setLastModificationTime(item.getLastModificationTime());
                    jingdongHomeData.setQueryMessage(item.getMessage());

                    // 线下库存为空
                    if(thirdData == null){
                        jingdongHomeData.setFixedFlag(false);
                        jingdongHomeData.setFixeMessage(null);
                    } else {
                        Long thirdDataInQty = thirdData.getInQty() == null ? 0L : thirdData.getInQty();
                        Long currentInQty = jingdongHomeData.getInQty() == null ? 0L : jingdongHomeData.getInQty();
                        jingdongHomeData.setFixedFlag(Long.compare(thirdDataInQty, currentInQty) != 0);
                        jingdongHomeData.setFixeMessage("库存同步");
                    }
                    resultList.add(jingdongHomeData);
                } else {
                    jingdongHomeData = new ProductStockSummaryGetAllResp();
                    jingdongHomeData.setType("jingdongHome");
                    jingdongHomeData.setOfflineStoreCode(offlineStoreCode);
                    jingdongHomeData.setOnlineStoreCode(null);
                    jingdongHomeData.setProductCode(productCode);
                    jingdongHomeData.setSkuCode(skuCode);
                    jingdongHomeData.setCurQty(null);
                    jingdongHomeData.setTranQty(null);
                    jingdongHomeData.setInQty(null);
                    jingdongHomeData.setPreQty(null);
                    jingdongHomeData.setLockQty(null);
                    jingdongHomeData.setLastModificationTime(null);
                    jingdongHomeData.setQueryMessage(stockResp.getMessage());
                    jingdongHomeData.setFixedFlag(false);
                    jingdongHomeData.setFixeMessage(null);
                    resultList.add(jingdongHomeData);
                }
            }
        }

        // 查询饿了么库存： 只有一个库存数据，作为现货库存处理
        ProductStockSummaryGetAllResp elemeData;
        String source = settingMap.get("elemeRetail.source");
        String secret = settingMap.get("elemeRetail.secret");
        if(source != null && !"".equals(source) && secret != null && !"".equals(secret)) {

            // 查询库存数据
            ElemeRetailGetSkuStockReqDTO stockQueryDTO = new ElemeRetailGetSkuStockReqDTO();
            stockQueryDTO.setOfflineStoreCode(offlineStoreCode);
            stockQueryDTO.setSkuCode(skuCode);
            BaseResult stockResp = dianDianElemeRetailExchangeClient.getSkuStock(source, secret, stockQueryDTO);

            // 解析处理响应数据
            if(stockResp != null) {
                // 查到库存数据
                if(stockResp.getCode() == 0 && stockResp.getData() != null){
                    ElemeRetailBusinessGetSkuStockRespDTO item = JSON.parseObject(JSON.toJSONString(stockResp.getData()), ElemeRetailBusinessGetSkuStockRespDTO.class);
                    elemeData = new ProductStockSummaryGetAllResp();
                    elemeData.setType("elemeRetail");
                    elemeData.setOfflineStoreCode(item.getOfflineStoreCode());
                    elemeData.setOnlineStoreCode(item.getOnlineStoreCode());
                    elemeData.setProductCode(item.getProductCode());
                    elemeData.setSkuCode(item.getSkuCode());
                    elemeData.setCurQty(item.getCurQty());
                    elemeData.setTranQty(item.getTranQty());
                    elemeData.setInQty(item.getInQty());
                    elemeData.setPreQty(item.getPreQty());
                    elemeData.setLockQty(item.getLockQty());
                    elemeData.setLastModificationTime(item.getLastModificationTime());
                    elemeData.setQueryMessage(item.getMessage());

                    // 线下库存为空
                    if(thirdData == null){
                        elemeData.setFixedFlag(false);
                        elemeData.setFixeMessage(null);
                    } else {
                        Long thirdDataInQty = thirdData.getInQty() == null ? 0L : thirdData.getInQty();
                        Long currentInQty = elemeData.getInQty() == null ? 0L : elemeData.getInQty();
                        elemeData.setFixedFlag(Long.compare(thirdDataInQty, currentInQty) != 0);
                        elemeData.setFixeMessage("库存同步");
                    }
                    resultList.add(elemeData);
                } else {
                    elemeData = new ProductStockSummaryGetAllResp();
                    elemeData.setType("elemeRetail");
                    elemeData.setOfflineStoreCode(offlineStoreCode);
                    elemeData.setOnlineStoreCode(null);
                    elemeData.setProductCode(productCode);
                    elemeData.setSkuCode(skuCode);
                    elemeData.setCurQty(null);
                    elemeData.setTranQty(null);
                    elemeData.setInQty(null);
                    elemeData.setPreQty(null);
                    elemeData.setLockQty(null);
                    elemeData.setLastModificationTime(null);
                    elemeData.setQueryMessage(stockResp.getMessage());
                    elemeData.setFixedFlag(false);
                    elemeData.setFixeMessage(null);
                    resultList.add(elemeData);
                }
            }
        }

        // 组装返回结构
        return resultList;
    }

    private Map<String, String> getAllSettingMap(String belong){
        Map<String, String> resultMap = new HashMap<>();

        BaseResult<List<ClientSettingGetByBelongRespDTO>> resp = dianDianClientClient.getByBelong(belong);
        if(resp != null && resp.getCode() == 0 && resp.getData() != null && resp.getData().size() > 0){
            List<ClientSettingGetByBelongRespDTO> itemList = resp.getData();
            for (int i = 0; i < itemList.size(); i++) {
                resultMap.put(itemList.get(i).getType() + "." + itemList.get(i).getParamKey(), itemList.get(i).getParamValue());
            }
        }

        return resultMap;
    }
}
